/**
 * OSAmI: Open Source Ambient Intelligence
 * A simple discovery protocol (based on multicast communications) for constrained devices.
 * Copyright (C) Lionel Debroux 2006 (as a TER/Magistere M1 student in the LSR-IMAG-ADELE team, for a demo in the H-Omega project)
 * Copyright (C) Lionel Debroux 2010 (as an engineer in the LCIS-INPG-CTSYS team, for a pre-demo in the FR part of the OSAMI project)
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
 */

package fr.imag.adele.homega.impl.discovery;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class Activator implements Runnable, BundleActivator {

	/// TODO: make configurable (JMX ? Config Admin ?)
	private String discoveryBridgeAddress = "FF02:0:0:0:0:0:0:99"; //"226.0.0.1";
	/// TODO: make configurable (JMX ? Config Admin ?)
	private int discoveryBridgePort = 0xF0B1; // 10001
	/// TODO: make configurable (JMX ? Config Admin ?)
	private int probeInterval = 10000; // in milliseconds, should be higher in production

	private DiscoveryBridge bridge = null;
	private Thread t = null;
	private boolean shouldStop = false;

	private static final int NAP_TIME = 1000; // in milliseconds

	@Override
	public void start(BundleContext bc) throws Exception {
		System.out.println("=== Starting discovery bridge ===");
		bridge = new DiscoveryBridgeImpl(discoveryBridgeAddress, discoveryBridgePort, null, null);
		t = new Thread(this);
		t.start();
	}

	@Override
	public void stop(BundleContext bc) throws Exception {
		System.out.println("=== Stopping discovery bridge ===");
		if (t != null)
		{
			shouldStop = true;
			while (shouldStop) {
				Thread.yield();
			}
		}
		if (bridge != null)
		{
			bridge.shutdown();
		}
	}

	@Override
	public void run() {
		System.out.println("=== Starting thread for discovery bridge ===");
		int i = 0;
		while (!shouldStop) {
			try {
				Thread.sleep(NAP_TIME);
				if ((i % (int)(probeInterval / NAP_TIME)) == 0) {
					if (bridge != null)
					{
						bridge.probe("*");
					}
				}
				i++;
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("=== Stopping thread for discovery bridge ===");
		shouldStop = false;
	}
}
